<template>
  <a-form-item label="" class="table-search-item">
    <a-select v-model:value="vdata.cycleType" @change="changeType">
      <a-select-option value="date">日报</a-select-option>
      <a-select-option v-if="isIncludeMonth" value="month">月报</a-select-option>
      <a-select-option v-if="isIncludeYear" value="year">年报</a-select-option>
    </a-select>
  </a-form-item>
  <a-space direction="vertical" :size="12">
    <a-range-picker v-model:value="vdata.date" :picker="vdata.cycleType" :disabled-date="disabledDate" @change="changeDate" />
  </a-space>
</template>
<script setup lang="ts">
import { reactive, watch, onMounted } from 'vue'
import dayjs, { Dayjs } from 'dayjs'
const emit = defineEmits(['changeDate', 'changeDateType'])
const props = defineProps({
  cycleType: { type: String, default:'date' },
  date: { type: String, default: '' },
  isIncludeMonth: { type: Boolean, default: false },
  isIncludeYear: { type: Boolean, default: false },
})

// 不能选择超过今天的日期
const disabledDate = (current: Dayjs) => {
  return current > dayjs().subtract(1, 'day')|| current < dayjs('2022-11-1 00:00:00')
}


const vdata = reactive({
  type: '日报',
  cycleType: 'date',//周期类型
  date: [] as any,
})

// 重置按钮，不能直接重置时间选择，需要通过watch监听，进行重置
watch( () => props.date ,(newVal,oldVal)=>{
  if (!props.date) {
    vdata.date = []
  }
})

onMounted(() => {
  if (props.cycleType) {
    vdata.cycleType = props.cycleType
  }
  if(!props.date){
    vdata.date = [dayjs().subtract(7, 'day'),dayjs().subtract(1, 'day')]
    changeDate(vdata.date)
  }
})

function changeType(e) {
  vdata.cycleType = e
  vdata.date = []
  emit('changeDateType', vdata.cycleType)
}

function changeDate(e) {
  if(!e) {
    emit('changeDate', undefined)
    return
  }
  let start = e[0].format('YYYY-MM-DD 00:00:00')
  let end = e[1].format('YYYY-MM-DD 23:59:59')
  let timeParameter = 'customDateTime_' + start + '_' + end
  let dateObject = reactive({
    startDate: start,
    endDate: end,
    timeParams: timeParameter
  })
  emit('changeDate', dateObject)
}
</script>